/*
 * Copyright 2013 Pavel Stastny <pavel.stastny at gmail.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.aplikator.server.processes.impl.processes.ipc.impl;

import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.aplikator.server.processes.impl.processes.ipc.IPCMessage;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * IPC message 
 * @author Pavel Stastny <pavel.stastny at gmail.com>
 */
public class IPCMessageImpl implements IPCMessage {

    public static void readMessage() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    
    private String sourceAddr;
    private String destAddr;
    
    private String body;

    public IPCMessageImpl(String sourceAddr, String destAddr, String body) {
        this.sourceAddr = sourceAddr;
        this.destAddr = destAddr;
        this.body = body;
    }
    
    @Override
    public String getSourceAddress() {
        return this.sourceAddr;
    }

    @Override
    public String getDestAddress() {
        return this.destAddr;
    }

    @Override
    public String getBody() {
        return this.body;
    }
    
    @Override
    public byte[] storeToBytes(Charset charset) {
        try {
            String str = message2String();
            return str.getBytes(charset);
        } catch (JSONException ex) {
            Logger.getLogger(IPCMessageImpl.class.getName()).log(Level.SEVERE, null, ex);
            return new byte[0];
        }
    }
    
    private String message2String() throws JSONException {
        JSONObject obj = new JSONObject();
        obj.put("from", this.getSourceAddress());
        obj.put("to", this.getDestAddress());
        obj.put("body", this.getBody());
        return obj.toString();
    }
    
    public static IPCMessage readMessageFromBytes(byte[] bytes, Charset charset) throws JSONException {
        JSONObject jsonObjc = new JSONObject(new String(bytes, charset));
        return new IPCMessageImpl(jsonObjc.getString("from"), jsonObjc.getString("to"), jsonObjc.get("body").toString());
    } 
    
}
